/*
* Copyright (c) 2015 Razeware LLC
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/

import UIKit
import QuartzCore
import CoreData

class ContainerViewController: UIViewController {
	
	let menuWidth: CGFloat = 80.0
	let animationTime: TimeInterval = 0.5
	
	let menuViewController: UIViewController!
	var centerViewController: UIViewController!
    //var centerViewController:CenterViewController!
	let orgCenterVC:UIViewController!
    //var orgCenterVC:CenterViewController!
	
	var isOpening = false
	
	var managedObjectContext:NSManagedObjectContext!
	var commitPredicate:NSPredicate?
	
	//let addKsVC:AddKsViewController!
	//let addKsVC:UIViewController!
	var contentVCs:[UIViewController] = [UIViewController]()
    //var contentVCs:[CenterViewController] = [CenterViewController]()
	var curContectVCIndex = 0
	
	var openPercent:CGFloat {
		return floor(centerViewController.view.frame.origin.x/menuWidth)
	}
	
	var panGesture:UIPanGestureRecognizer!
	
	func switchContentVC(to index:Int){
		defer {
			toggleSideMenu()
		}
		
		guard index >= 0 && index < contentVCs.count else {return}
		guard index != curContectVCIndex else {return}
		
		let vc = contentVCs[index]
		vc.view.frame = centerViewController.view.frame
		centerViewController.view.isHidden = true
		
		centerViewController = vc
		setContentVCMenuItem(vc: centerViewController, index: index)
		
		if let centerVC = centerVC(vc: vc){
			centerVC.enterBlock?()
		}
		
		vc.view.isHidden = false
		curContectVCIndex = index
	}
	
	func centerVC(vc:UIViewController)->CenterViewController?{
		if let nav = vc as? UINavigationController{
			if let center = nav.viewControllers.first as? CenterViewController{
				return center
			}
		}
		return nil
	}
	
	func setContentVCMenuItem(vc:UIViewController,index:Int){
		if let contentVC = (vc as! UINavigationController).viewControllers.first as? CenterViewController{
			contentVC.menuItem = MenuItem.sharedItems[index]
		}
	}
	
	func setContainerRef(vc:UIViewController){
		let contentVC = (vc as! UINavigationController).viewControllers.first as! CenterViewController
		contentVC.containerVC = self
	}
	
	func initContentVCBy(id:String)->UIViewController{
		let storyboard = UIStoryboard(name: "Main", bundle: nil)
		let vc = storyboard.instantiateViewController(withIdentifier: id)
		addChildViewController(vc)
		view.addSubview(vc.view)
		vc.view.isHidden = true
		vc.didMove(toParentViewController: self)
		setContainerRef(vc: vc)
		
		return vc
	}
	
	func initContentVCs(){
		addChildViewController(orgCenterVC)
		view.addSubview(orgCenterVC.view)
		orgCenterVC.didMove(toParentViewController: self)
		setContainerRef(vc: orgCenterVC)
		
		let addKsVC = initContentVCBy(id: "AddKsVC")
		let listKsVC = initContentVCBy(id: "ListKsVC")
		
		if orgCenterVC != nil{
			let count = MenuItem.sharedItems.count
			for _ in 0..<count{
				contentVCs.append(orgCenterVC)
			}
			
			contentVCs[0] = listKsVC
			setContentVCMenuItem(vc: listKsVC, index: 0)
			contentVCs[1] = addKsVC
			
			contentVCs[0].view.isHidden = false
			centerViewController = contentVCs[0]
		}
	}
	
	init(sideMenu: UIViewController, center: UIViewController) {
		menuViewController = sideMenu
		centerViewController = center
		orgCenterVC = center
		orgCenterVC.view.isHidden = true
		
		super.init(nibName: nil, bundle: nil)
		
		initContentVCs()
	}
	
	required init(coder aDecoder: NSCoder) {
		fatalError("init(coder:) has not been implemented")
	}
	
	func menuTransformForPercent(_ percent:CGFloat)->CATransform3D{
		var identity = CATransform3DIdentity
		identity.m34 = -1.0/1000
		
		let remainingPercent = 1.0 - percent
		let angle = remainingPercent * CGFloat(-M_PI_2)
		
		let rotationTransform = CATransform3DRotate(identity, angle, 0.0, 1.0, 0.0)
		let translationTransform = CATransform3DMakeTranslation(menuWidth * percent, 0, 0)
		return CATransform3DConcat(rotationTransform, translationTransform)
	}
	
	
	override var preferredStatusBarStyle : UIStatusBarStyle {
		return .lightContent
	}
	
	override func viewDidLoad() {
		
		super.viewDidLoad()
		view.backgroundColor = UIColor.black
		setNeedsStatusBarAppearanceUpdate()
		
		
		addChildViewController(menuViewController)
		view.addSubview(menuViewController.view)
		menuViewController.didMove(toParentViewController: self)
		
		menuViewController.view.layer.anchorPoint.x = 1.0
		menuViewController.view.frame = CGRect(x: -menuWidth, y: 0, width: menuWidth, height: view.frame.height)
		
		panGesture = UIPanGestureRecognizer(target:self, action:#selector(ContainerViewController.handleGesture(_:)))
		view.addGestureRecognizer(panGesture)
		
		//let tapGesture = UITapGestureRecognizer(target: self, action: #selector(ContainerViewController.tapHandler(_:)))
		//view.addGestureRecognizer(tapGesture)
		
		setToPercent(0.0)
		
		//deleteDBFiles()
		initCoreData()
		//testInsertKs()
        //print(getDocumentsDirectory())
	}
	
	func tapHandler(_ recognizer:UITapGestureRecognizer){
		if openPercent == 1.0 {
			toggleSideMenu()
		}
	}
	
	func handleGesture(_ recognizer: UIPanGestureRecognizer) {
		
		let translation = recognizer.translation(in: recognizer.view!.superview!)
		
		var progress = translation.x / menuWidth * (isOpening ? 1.0 : -1.0)
		progress = min(max(progress, 0.0), 1.0)
		
		switch recognizer.state {
		case .began:
			let isOpen = floor(centerViewController.view.frame.origin.x/menuWidth)
			isOpening = isOpen == 1.0 ? false: true
			
			menuViewController.view.layer.shouldRasterize = true
			menuViewController.view.layer.rasterizationScale = UIScreen.main.scale
		case .changed:
			self.setToPercent(isOpening ? progress: (1.0 - progress))
			
		case .ended: fallthrough
		case .cancelled: fallthrough
		case .failed:
			
			var targetProgress: CGFloat
			if (isOpening) {
				targetProgress = progress < 0.5 ? 0.0 : 1.0
			} else {
				targetProgress = progress < 0.5 ? 1.0 : 0.0
			}
			
			UIView.animate(withDuration: animationTime, animations: {
				self.setToPercent(targetProgress)
			}, completion: {_ in
				self.menuViewController.view.layer.shouldRasterize = false
			})
			
		default: break
		}
	}
	
	func toggleSideMenu() {
		let isOpen = floor(centerViewController.view.frame.origin.x/menuWidth)
		let targetProgress: CGFloat = isOpen == 1.0 ? 0.0: 1.0
		
		UIView.animate(withDuration: animationTime, animations: {
			self.setToPercent(targetProgress)
		}, completion: { _ in
			self.menuViewController.view.layer.shouldRasterize = false
		})
	}
	
	func buttonTransformForPercent(_ percent: CGFloat) -> CATransform3D {
		
		var identity = CATransform3DIdentity
		identity.m34 = -1.0/1000
		
		let angle = percent * CGFloat(-M_PI)
		let rotationTransform = CATransform3DRotate(identity, angle, 1.0, 1.0, 0.0)
		
		return rotationTransform
	}
	
	func setToPercent(_ percent: CGFloat) {
		centerViewController.view.frame.origin.x = menuWidth * CGFloat(percent)
		menuViewController.view.layer.transform = menuTransformForPercent(percent)
		menuViewController.view.alpha = CGFloat(max(0.2, percent))
		
        let vc = centerViewController as UIViewController
		if let centerVC = (vc as! UINavigationController).viewControllers.first as? CenterViewController{
			if let menuButton = centerVC.menuButton{
				menuButton.imageView?.layer.transform = buttonTransformForPercent(percent)
			}
		}
	}
	
}
